<?php

namespace App\Http\Controllers\admin\product;

use App\Http\Controllers\Controller;
use App\Models\product\ProductBelongModel;
use App\Models\product\ProductClassModel;
use App\Models\product\ProductCommissionRuleModel;
use App\Models\product\ProductModel;
use App\Models\product\ProductPopularizeModel;
use App\Models\product\ProductSonModel;
use App\Service\admin\ProductService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use lxs\api\ApiResponse;
use lxs\tools\Tools;

class ProductController extends Controller
{

    /**
     * 获取产品列表页面数据
     */
    public function getProductListData(): JsonResponse
    {
        $data = request()->input();

        if (isset($data['tab']) && $data['tab'] == 1) {
            $query = ProductModel::with(['productClass', 'productBelong'])
                ->where('deleted_at', 0)
                ->where('status', 1);
        } else if (isset($data['tab']) && $data['tab'] == 2) {
            $query = ProductModel::with(['productClass', 'productBelong'])
                ->where('deleted_at', 0)
                ->where('status', 2);
        } else {
            $query = ProductModel::with(['productClass', 'productBelong'])
                ->where('deleted_at', 0);
        }

        if ($data['keywords'] != '') {
            $query->where('product_title', 'like', '%' . $data['keywords'] . '%');
        }

        if ($data['product_type'] > 0) {
            $query->where('product_type', $data['product_type']);
        }

        if ($data['class_id'] > 0) {
            $query->where('class_id', $data['class_id']);
        }

        if ($data['belong_id'] > 0) {
            $query->where('belong_id', $data['belong_id']);
        }

        if ($data['online_platform'] > 0) {
            $query->where('online_platform', $data['online_platform']);
        }

        $lists = $query->orderBy('sort', 'asc')
            ->orderBy('sort_pid', 'asc')
            ->paginate($data['pageSize']);
        foreach ($lists as $item) {
            $item->live_time = Tools::timeConvert($item->live_time);
            $item->product_type_name = ProductModel::getProductType($item->product_type);
            $item->online_platform_name = ProductModel::getOnlinePlatform($item->online_platform);
            $item->popularize_data = ProductPopularizeModel::whereIn('id', explode(',', $item->popularize_platform))->get();
            $item->online_platform_num = ProductModel::where('product_title', $item->product_title)->count();
            $item->commission_ratio = ProductService::instance()->getProductCommissionRatio($item->commission_ratio,
                $item->belong_id, $item->class_id);
        }

        $productTypeData = ProductModel::getProductType();

        $productClassData = ProductClassModel::where('deleted_at', 0)->get();

        $productBelongData = ProductBelongModel::where('deleted_at', 0)->get();

        $onlinePlatformData = ProductModel::getOnlinePlatform();


        return ApiResponse::apiResponseData(200, '获取商品列表数据成功', [
            'lists' => $lists,
            'productTypeData' => $productTypeData,
            'productClassData' => $productClassData,
            'productBelongData' => $productBelongData,
            'onlinePlatformData' => $onlinePlatformData,
        ]);
    }


    /**
     * 删除产品提交
     */
    public function productDeleteSubmit(): JsonResponse
    {
        $id = request()->input('id');

        $lists = ProductSonModel::where('product_id', $id)->get();
        if ($lists) {
            try {
                DB::beginTransaction();
                foreach ($lists as $v) {
                    ProductSonModel::where('id', $v->id)->update(['deleted_at' => time(),]);
                }
                DB::commit();
                return ApiResponse::apiResponseData(200, '删除成功');
            } catch (\Exception $e) {
                DB::rollBack();
                Log::error($e->getMessage());
                return ApiResponse::apiResponseData(500, '删除失败');
            }
        }
        return ApiResponse::apiResponseData(200, '删除成功');
    }


    /**
     * 获取产品详情表单数据
     */
    public function getProductFormData(): JsonResponse
    {
        $product_id = request()->input('id');

        $sameProductPlatform = [
            0 => [
                'id' => '',
                'popularize_platform' =>  ProductPopularizeModel::get()->toArray(),
                'platform_product_title' => '',
                'appid' => '',
                'secret' => '',
                'public_key' => '',
                'path' => '',
                'platform_link' => ''
            ],
        ];
        $platformData = [];
        if ( $lists = ProductModel::find($product_id) ) {

            $lists->live_time = (new Carbon($lists->live_time))->format('Y-m-d H:i:s');
            $lists->product_type = ProductModel::getProductType($lists->product_type);
            $lists->online_platform = ProductModel::getOnlinePlatform($lists->online_platform);

            $sameProductPlatform = ProductSonModel::where('product_id', $product_id)
                ->where('deleted_at', 0)
                ->get()->toArray();
            foreach ($sameProductPlatform as $k => $v) {
                $sameProductPlatform[$k]['popularize_platform'] = ProductPopularizeModel::get()->toArray();

                $popularizeInfo = ProductPopularizeModel::where('id', $v['popularize_id'])->first();
                $platformData[$k]['id'] = $v['id'];
                $platformData[$k]['popularize_platform'] = $popularizeInfo->id;
                $platformData[$k]['platform_product_title'] = $lists['product_title'] . '(' . $popularizeInfo->popularize_name . ')';
                $platformData[$k]['appid'] = $v['appid'];
                $platformData[$k]['secret'] = $v['secret'];
                $platformData[$k]['public_key'] = $v['public_key'];
                $platformData[$k]['path'] = $v['path'];
                $platformData[$k]['platform_link'] = $v['platform_link'];
            }

        }

        $productType = ProductModel::getProductType();

        $classData = ProductClassModel::where('deleted_at', 0)->get();

        $belongData = ProductBelongModel::where('deleted_at', 0)->get();

        $onlinePlatformData = ProductModel::getOnlinePlatform();

        return ApiResponse::apiResponseData(200, '获取商品详情表单数据成功', [
            'lists' => $lists,
            'sameProductPlatform' => $sameProductPlatform,
            'platformData' => $platformData,
            'productType' => $productType,
            'classData' => $classData,
            'belongData' => $belongData,
            'onlinePlatformData' => $onlinePlatformData,
        ]);
    }


    /**
     * 产品表单添加Table数据
     */
    public function productFormAddTableData(): JsonResponse
    {
        $lists = [
            'id' => '',
            'popularize_platform' =>  ProductPopularizeModel::get()->toArray(),
            'platform_product_title' => '',
            'appid' => '',
            'secret' => '',
            'public_key' => '',
            'path' => '',
            'platform_link' => ''
        ];
        return ApiResponse::apiResponseData(200, '获取产品表单添加Table数据成功', [
            'lists' => $lists,
        ]);
    }


    /**
     * 产品表单选择推广平台自动生成产品名称
     */
    public function productFormGetPlatformName(): JsonResponse
    {
        $popularize_id = request()->input('popularize_id');
        $online_platform = request()->input('online_platform');
        $product_title = request()->input('product_title');
        if ($popularize_id) {
            $product_id = ProductModel::where('online_platform', $online_platform)->where('product_title', $product_title)->value('id');
            $list = ProductSonModel::where('deleted_at', 0)->where('product_id', $product_id)->where('popularize_id', $popularize_id)->first();
            if ($list) {
                return ApiResponse::error('该平台产品已存在');
            }
            $value = ProductPopularizeModel::where('id', $popularize_id)->value('popularize_name');
            $product_title = $product_title . '（' . $value . '）';
            return ApiResponse::apiResponseData(200, '获取产品表单选择推广平台自动生成产品名称成功', [
                'product_title' => $product_title,
            ]);
        }
        return ApiResponse::error('请选择推广平台');
    }


    /**
     * 产品表单数据提交
     */
    public function productFormSubmit(): JsonResponse
    {
        $post = request()->input();

        $validator = Validator::make($post, [
            'product_title' => 'required',
            'product_type' => 'required',
            'class_id' => 'required',
            'belong_id' => 'required',
            'online_platform' => 'required',
            'product_cover' => 'required',
            'live_time' => 'required|date',
            'product_intro' => 'required|min:10|max:250',
        ], [
            'product_title.required' => '请输入产品名称',
            'product_type.required' => '请选择产品类型',
            'class_id.required' => '请选择产品分类',
            'belong_id.required' => '请选择产品所属',
            'online_platform.required' => '请选择上线平台',
            'product_cover.required' => '请上传产品封面',
            'live_time.required' => '请选择产品直播时间',
            'live_time.date' => '请选择产品直播时间',
            'product_intro.required' => '请输入产品简介',
            'product_intro.min' => '请输入产品简介10-250个字符',
            'product_intro.max' => '请输入产品简介10-250个字符',
        ]);

        if ($validator->fails()) {
            return ApiResponse::error($validator->errors()->first());
        }

        $result = ProductService::instance()->productFromSubmit($post);

        if ($result['code'] == 200) {
            return ApiResponse::apiResponseData(200, $result['message']);
        } else {
            return ApiResponse::apiResponseData($result['code'], $result['message']);
        }
    }


    /**
     * 获取产品分类列表页面数据
     */
    public function getProductClassListData(): JsonResponse
    {
        $data = request()->input();
        $lists = ProductClassModel::where('deleted_at', 0)
            ->orderBy('sort', 'asc')
            ->orderBy('create_time', 'desc')
            ->paginate($data['pageSize']);

        return ApiResponse::apiResponseData(200, '获取商品分类列表页面数据成功', [
            'lists' => $lists
        ]);
    }


    /**
     * 删除产品分类
     */
    public function productClassDeleteSubmit(): JsonResponse
    {
        $class_id = request()->input('id');

        if (ProductModel::where('class_id', $class_id)->count() > 0) {
            return ApiResponse::apiResponseData(400, '该分类下有产品，不能删除');
        }

        try {
            DB::beginTransaction();

            $productClass = ProductClassModel::find($class_id);
            $productClass->delete();

            $belongData = ProductBelongModel::where('deleted_at', 0)->get()->toArray();
            array_map(function ($item) use ($class_id) {
                $commissionInfo = ProductCommissionRuleModel::where('belong_id', $item['id'])
                    ->where('class_id', $class_id)
                    ->where('deleted_at', 0)
                    ->first();
                if ($commissionInfo) {
                    ProductCommissionRuleModel::where('id', $commissionInfo->id)->delete();
                }
            }, $belongData);

            DB::commit();
            return ApiResponse::apiResponseData(200, '删除成功');
        } catch (\Exception $e) {
            DB::rollBack();
            log::error(date('Y-m-d h:i:s',time()).' 产品分类删除失败:'.$e->getMessage());
            return ApiResponse::apiResponseData(400, '删除失败');
        }
    }


    /**
     * 获取产品分类表单数据
     */
    public function getProductClassFormData(): JsonResponse
    {
        $class_id = request()->input('id');

        $lists = [];
        if ($class_id > 0) {
            $lists = ProductClassModel::find($class_id);
        }

        return ApiResponse::apiResponseData(200, '获取商品分类表单数据成功', [
            'lists' => $lists
        ]);
    }


    /**
     * 产品分类表单数据提交
     */
    public function productClassFormSubmit(): JsonResponse
    {
        $post = request()->input();

        if (isset($post['id'])) {
            $productClass = ProductClassModel::find($post['id']);
        } else {
            $productClass = new ProductClassModel();
            $productClass->create_time = Carbon::now()->timestamp;
        }
        try {
            DB::beginTransaction();

            $productClass->class_name = $post['class_name'];
            $productClass->save();

            $belongData = ProductBelongModel::where('deleted_at', 0)->get();
            if ($belongData) {
                $belongData = $belongData->toArray();
                foreach ($belongData as $item) {
                    $commissionData = ProductCommissionRuleModel::where('deleted_at', 0)
                        ->where('belong_id', $item['id'])
                        ->where('class_id', $productClass->id)
                        ->first();
                    if (!$commissionData) {
                        $commissionData = new ProductCommissionRuleModel();
                        $commissionData->belong_id = $item['id'];
                        $commissionData->class_id = $productClass->id;
                        $commissionData->commission_rate = 0.1;
                        $commissionData->save();
                    }
                }
            }

            DB::commit();
            return ApiResponse::apiResponseData(200, '提交成功');
       } catch (\Exception $e) {
            DB::rollBack();
            log::error(date('Y-m-d h:i:s',time()).' 产品分类表单数据提交失败:'.$e->getMessage());
            return ApiResponse::apiResponseData(400, '提交失败');
       }
   }


    /**
     * 产品上下架表单提交
     */
    public function productStatusFormSubmit(): JsonResponse
    {
        $id = request()->input('id');
        $status = request()->input('status');
        try {
            DB::beginTransaction();
            $product = ProductModel::find($id);
            $product->status = $status;
            $product->save();
            DB::commit();
            return ApiResponse::apiResponseData(200, '提交成功');
        } catch (\Exception $e) {
            DB::rollBack();
            log::error(date('Y-m-d h:i:s',time()).' 产品上下架表单数据提交失败:'.$e->getMessage());
            return ApiResponse::apiResponseData(400, '提交失败');
        }
    }


   /**
    * 产品权重表单提交
    */
   public function productWeightFormSubmit(): JsonResponse
   {
       $post = request()->input();

       try {
           DB::beginTransaction();
           if (isset($post['id'])) {

               $product = ProductModel::find($post['id']);
               $product->sort = $post['sort'];
               $product->sort_pid = 1;
               $product->save();

               $sortList = ProductModel::where('deleted_at', 0)->where('sort', $post['sort'])->where('id', '<>', $post['id'])->orderBy('sort_pid', 'asc')->get()
                   ->toArray();
               if ($sortList) {
                   foreach ($sortList as $k => $v) {
                       $sort_pid = $product->sort_pid + $k + 1;
                       ProductModel::where('id', $v['id'])->update(['sort_pid' => $sort_pid]);
                   }
               }
               DB::commit();
               return ApiResponse::apiResponseData(200, '提交成功');
           }
           return ApiResponse::apiResponseData(400, '获取产品权重失败');
       } catch (\Exception $e) {
           DB::rollBack();
           log::error(date('Y-m-d h:i:s',time()).' 产品权重表单提交失败:'.$e->getMessage());
           return ApiResponse::apiResponseData(400, '提交失败');
       }
   }



}
